
#import "NSDataAdditions.h"

@implementation NSData(Additions)

//
// base64 encoding
//
- (NSString*)encodeBase64
{
	static char const* table64												= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
	uint8_t const* inputChar												= (uint8_t const*)self.bytes;
	NSInteger inputLength													= self.length;
	
	NSString* retValue														= [[[NSString alloc] init] autorelease];
	while(inputLength)
	{
		uint8_t iBuf[3]														= {0};
		char oBuf[5]														= {0};
		NSInteger inputParts												= 0;
		for(NSInteger i = 0; i < 3; i ++)
		{
			if(inputLength)
			{
				inputParts													+= 1;
				iBuf[i]														= *inputChar;
				inputChar													+= 1;
				inputLength													-= 1;
			}
			else
			{
				iBuf[i]														= 0;
			}
		}
		
		oBuf[0]																= table64[(iBuf[0] & 0xfc) >> 2];
		oBuf[1]																= table64[((iBuf[0] & 0x03) << 4) | ((iBuf[1] & 0xf0) >> 4)];
		oBuf[2]																= inputParts > 1 ? table64[((iBuf[1] & 0x0f) << 2) | ((iBuf[2] & 0xc0) >> 6)] : '=';
		oBuf[3]																= inputParts > 2 ? table64[iBuf[2] & 0x3f] : '=';
		
		retValue															= [retValue stringByAppendingFormat:@"%s", oBuf];
	}
	
	return retValue;
}

@end
